package com.ccsu.joysport.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class OssUploadUtil {

    // 阿里云OSS endpoint，不同区域的endpoint不同，请根据你的Bucket所在区域进行替换
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    // 阿里云账号AccessKeyId
    private static final String ACCESS_KEY_ID = "LTAI5tNuuHaYKiXnxCBQvGSa";
    // 阿里云账号AccessKeySecret
    private static final String ACCESS_KEY_SECRET = "yRjwDhYWg8x7JtsNKBAPdJkUOr2yQO";
    // 存储桶名称
    private static final String BUCKET_NAME = "joy-sport";

    private static final String DIRECTORY = "ccsu";

    public static String uploadFile(MultipartFile file) {

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        String fileName = getFileName(file);

        try {
            // 设置上传文件的元数据，这里设置为公共读权限，以便获取公网访问的URL
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setObjectAcl(com.aliyun.oss.model.CannedAccessControlList.PublicRead);

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, file.getInputStream(), metadata);

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 生成公网访问的URL
            return "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private static String getFileName(MultipartFile file) {
        // 兜底默认jpg
        String fileExtName = ".jpg";

        if (file != null && !file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename != null) {
                fileExtName =  "." + FilenameUtils.getExtension(originalFilename);
            }
        }

        String date = new SimpleDateFormat("yyMMdd").format(new Date());
        return DIRECTORY + "/" + date + "/" + date + UUID.randomUUID().toString().replace("-", "") + fileExtName;
    }

}